package com.gaohc.system.sysdict.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaohc.common.constant.UserConstants;
import com.gaohc.common.core.domain.entity.SysDictData;
import com.gaohc.common.core.domain.entity.SysDictType;
import com.gaohc.common.utils.DictUtils;
import com.gaohc.common.utils.StringUtils;
import com.gaohc.system.sysdict.mapper.SysDictTypeMapper;
import com.gaohc.system.sysdict.ISysDictDataService;
import com.gaohc.system.sysdict.ISysDictTypeService;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

import static com.gaohc.common.utils.DictUtils.clearDictCache;

/**
 * 字典 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements ISysDictTypeService {

    @Resource
    private ISysDictDataService sysDictDataService;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init()
    {
        loadingDictCache();
    }

    /**
     * 根据字典类型查询字典数据
     * 
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType)
    {
        List<SysDictData> dictDatas = DictUtils.getDictCache(dictType);
        if (StringUtils.isNotEmpty(dictDatas))
        {
            return dictDatas;
        }
        dictDatas = sysDictDataService.lambdaQuery()
                .eq(SysDictData::getStatus, 0)
                .eq(SysDictData::getDictType, dictType)
                .orderByAsc(SysDictData::getDictSort).list();
        if (StringUtils.isNotEmpty(dictDatas))
        {
            DictUtils.setDictCache(dictType, dictDatas);
            return dictDatas;
        }
        return null;
    }
    @Override
    public String checkDictTypeUnique(SysDictType dict)
    {
        long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
        SysDictType dictType = lambdaQuery().eq(SysDictType::getDictType, dict.getDictType()).one();
        if (StringUtils.isNotNull(dictType) && dictType.getDictId() != dictId)
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public void resetDictCache() {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 加载字典缓存数据
     */
    public void loadingDictCache()
    {
        List<SysDictType> dictTypeList = this.list();
        for (SysDictType dictType : dictTypeList)
        {
            List<SysDictData> dictDatas = sysDictDataService.lambdaQuery()
                    .eq(SysDictData::getStatus, 0)
                    .eq(SysDictData::getDictType, dictType)
                    .orderByAsc(SysDictData::getDictSort).list();
            DictUtils.setDictCache(dictType.getDictType(), dictDatas);
        }
    }

}
